package com.kin207.netty.tcp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.server.ServerAbs;
import com.kin207.netty.session.SessionManager;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TcpServer extends ServerAbs {
	final static Logger logger = LoggerFactory.getLogger(TcpServer.class);
	
	public TcpServer(int port) {
		super(port);
	}

	public void run() throws InterruptedException {
		if(sessionManager==null){
			sessionManager = new SessionManager();
		}
		EventLoopGroup parentGroup = new NioEventLoopGroup();
		EventLoopGroup childGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(parentGroup, childGroup);
			b.channel(NioServerSocketChannel.class);
			b.childHandler(channelInitializer);
			
			channelFuture = b.bind(port).sync();
			
			logger.info("tcp server run success.");
			postCreatedEvent(this);
			channelFuture.channel().closeFuture().sync();
		} finally {
			childGroup.shutdownGracefully();
			parentGroup.shutdownGracefully();
		}
		logger.info("tcp server close.");
		postDestroyedEvent(this);
	}

	public String getServerType() {
		return "tcp";
	}

	public void close() {
		channelFuture.channel().close();
	}

}
